﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Threading.Tasks;
using Brc_DSB.GetWay.Configuration;
using Brc_DSB.GetWay.Model;
using Dapper;
using Ocelot.Cache;

namespace Brc_DSB.GetWay.DataBase
{
    public class WebServiceRepository : IWebServiceRepository
    {
        private readonly DbConfiguration _option;
        private readonly IOcelotCache<GetWay_WebService> _cache;
        public WebServiceRepository(DbConfiguration option, IOcelotCache<GetWay_WebService> cache)
        {
            _option = option;
            _cache = cache;
        }
        public async Task<GetWay_WebService> GetService(string serviceName)
        {
            var sql = @"
SELECT * FROM [dbo].[GetWay_WebService] WHERE ServiceName=@serviceName
";
            using (var connection = new SqlConnection(_option.DbConnectionStrings))
            {
                //如果启用了权限缓存，那么久先从缓存中取，取不到就去数据库取，然后放入缓存
                GetWay_WebService serviceResult = null;
                var key = serviceName;
                if (_option.IsEnableRetry)
                {

                    serviceResult = _cache.Get(key, "Service");
                }
                if (serviceResult == null)
                {
                    try
                    {
                        serviceResult = await connection.QueryFirstOrDefaultAsync<GetWay_WebService>(sql, new { serviceName });
                        _cache.Add(key, serviceResult, TimeSpan.FromMinutes(_option.ServiceCacheTime), "Service");
                    }
                    catch (Exception e)
                    {
                        throw e;
                    }
                }
                return serviceResult;
            }
        }
    }
}
